const { join } = require('path');
const { existsSync, statSync, readFileSync, mkdirSync, writeFileSync } = require('fs');
const { app } = require('@electron/remote');
//获取用户数据目录
const userData = app.getPath('userData');
// 获取主题
export function readTheme() {
  let themePath = join(app.isPackaged ? userData : process.cwd(), '.markdown-k', 'theme');
  let themeFile = join(themePath, 'theme.json');

  if (existsSync(themeFile) && statSync(themeFile).size > 0) {
    let theme = JSON.parse(readFileSync(themeFile, 'utf8'));
    setTheme(theme);
    return theme;
  } else {
    if (!existsSync(themePath)) {
      // 以递归的方式创建目录
      mkdirSync(themePath, { recursive: true });
    }
    writeFileSync(themeFile, JSON.stringify(configTheme()));
    readTheme();
  }
}

// 保存主题
export function writeTheme(theme: object) {
  let themePath = join(app.isPackaged ? userData : process.cwd(), '.markdown-k', 'theme');
  let themeFile = join(themePath, 'theme.json');
  writeFileSync(themeFile, JSON.stringify(theme));
  readTheme();
}

// 默认主题
export function configTheme() {
  return {
    headBackgroundColor: '#eee8d5',
    headButtonMouseHoverBackgroundColor: '#d8d4ca',
    headIconColor: '#000',
    theHeadClosedButtonHoveringBackgroundColor: '#e82636',
    theHeadClosedButtonHoveringIconColor: '#fff',
    headFontColor: '#000',
    backgroundColor: '#fdf6e3',
    editorSToolbarPictureColor: '#000',
    editorSRightToolbarSelectedBackgroundColor: '#f0ece1',
    editorSRightToolbarSelectIconColor: '#fff',
    enterTheBackgroundColor: '#eee8d5'
  };
}

// 设置主题
export function setTheme(theme: any) {
  document.documentElement.style.setProperty('--header-backgroundColor', theme.headBackgroundColor);
  document.documentElement.style.setProperty('--backgroundColor', theme.backgroundColor);
  document.documentElement.style.setProperty('--header-hoverBackgroundColor', theme.headButtonMouseHoverBackgroundColor);
  document.documentElement.style.setProperty('--header-iconColor', theme.headIconColor);
  document.documentElement.style.setProperty('--header-close-hoverBackgroundColor', theme.theHeadClosedButtonHoveringBackgroundColor);
  document.documentElement.style.setProperty('--header-close-hoverIconColor', theme.theHeadClosedButtonHoveringIconColor);
  document.documentElement.style.setProperty('--header-fontColor', theme.headFontColor);
  document.documentElement.style.setProperty('--editor__toolbarColor', theme.editorSToolbarPictureColor);
  document.documentElement.style.setProperty('--actice-editor__toolbar-backgroundColor', theme.editorSRightToolbarSelectedBackgroundColor);
  document.documentElement.style.setProperty('--active-editor__toolbarColor', theme.editorSRightToolbarSelectIconColor);
  document.documentElement.style.setProperty('--enterBackgroundColor', theme.enterTheBackgroundColor);
}
